<template>
	<div class="alarm-notice">
		<div class="container">
			<div class="email-setting">
				<div class="title">
					<span>邮件告警设置</span>
					<el-switch v-model="emailSwitch" active-text="开启" inactive-text="关闭" @change="emailSwitchChange"/>
				</div>
				<div class="form-box">
					<el-form
						ref="emailRef"
						:inline="true"
						label-width="140px"
						:rules="emailFormRules"
						:model="emailForm" >
						<el-form-item label="SMTP服务器地址:" prop="stmpAddress">
							<el-input placeholder="请输入服务器ip或域名" v-model="emailForm.stmpAddress"/>
						</el-form-item>
						<el-form-item label="端口号:" prop="port">
							<el-input placeholder="请输入服务器端口号" v-model="emailForm.port"/>
						</el-form-item>
						<el-form-item label="SMTP用户名:" prop="stmpUserName">
							<el-input placeholder="admin@example.com" v-model="emailForm.stmpUserName"/>
						</el-form-item>
						<el-form-item label="SMTP用户密码:" prop="stmpPwd">
							<!-- forbidden chrome autocomplete -->
							<el-input type="password" autocomplete="new-password" v-model="emailForm.stmpPwd" show-password style="display: none;"/>
							<el-input type="password" autocomplete="new-password" v-model="emailForm.stmpPwd" show-password/>
						</el-form-item>
						<el-form-item label="发件人邮箱:" prop="senderEmail">
							<el-input placeholder="admin@example.com" v-model="emailForm.senderEmail"/>
						</el-form-item>
						<el-form-item  label="使用SSL安全连接:" prop="ssl">
							<el-switch v-model="emailForm.ssl"/>
						</el-form-item>
					</el-form>

					<div class="receive-list">
						<p>接收人:</p>
						<el-form style="height:auto" ref="addEmailContact" :model="emailContactsInput" :rules="rules">
							<div class="input-box">
								<el-form-item  prop="name">
									<el-input placeholder="user@example.com"  v-model="emailContactsInput.name"/>
								</el-form-item>
								<el-button @click="handleAddContacts(0)" type="primary">添加</el-button>
							</div>
						</el-form >
						<div class="data-list">
							<div class="data-item" v-for="user in emailReceiveList" :key="user.id">
								<el-tooltip :content="user.contactAccount" :enterable="false" :show-after="1000">
									<span @click="handleClickContacts(0,user)">{{ user.contactAccount }}</span>
								</el-tooltip>
								<SvgIcon name="ele-Delete" @click="delContacts(0,user)"/>
							</div>
						</div>
						<div class="btn-box">
							<el-button type="primary" @click="handleTest(0)">验证</el-button>
							<el-button type="danger" @click="resetSetting(0)">重置</el-button>
							<el-button type="primary" @click="handleSave(0)">保存</el-button>
						</div>
					</div>

				</div>
			</div>

			<div class="message-setting">
				<div class="title">
					<span>短信告警设置</span>
					<el-switch v-model="messageSwitch" active-text="开启" inactive-text="关闭" @change="messageSwitchChange"/>
				</div>
				<div class="form-box">
					<el-form
						ref="messageRef"
						:inline="true"
						label-width="135px"
						:model="messageForm"
						:rules="messageFormRules">
						<el-form-item label="短信服务商:">
							<el-select  placeholder="请选择短信服务商" v-model="messageForm.serviceProvider">
								<el-option
									v-for="item in serviceProvideOptions"
									:key="item.value"
									:label="item.label"
									:value="item.value"
								/>
							</el-select>
						</el-form-item>
						<el-form-item label="域名:" prop="domain">
							<el-input placeholder="请输入短信服务平台域名" v-model="messageForm.domain"/>
						</el-form-item>
						<el-form-item label="平台访问密钥id:" prop="accessKeyId">
							<el-input placeholder="短信服务密码ID，用于安全验证" v-model="messageForm.accessKeyId"/>
						</el-form-item>
						<el-form-item label="平台访问密钥key:" prop="accessKey">
							<el-input placeholder="短信服务秘钥，用于安全验证" v-model="messageForm.accessKey"/>
						</el-form-item>
						<el-form-item label="签名:" prop="sign">
							<el-input placeholder="请输入服务商通过的短信签名" v-model="messageForm.sign"/>
						</el-form-item>
						<el-form-item label="模板Code:" prop="templateCode">
							<el-input placeholder="服务商审核通过的短信模板Code" v-model="messageForm.templateCode"/>
						</el-form-item>
						<el-form-item label="地域ID:"  v-if="isShowMessageItem" prop="regionId">
							<el-select  placeholder="请输入所在地域对应的ID" v-model="messageForm.regionId">
								<el-option
									v-for="item in regionOptions"
									:key="item.value"
									:label="item.label"
									:value="item.value"
								/>
							</el-select>
						</el-form-item>
						<el-form-item label="应用ID:"  v-if="isShowMessageItem" prop="appId">
							<el-input placeholder="请输入所在地域对应的ID" v-model="messageForm.appId"/>
						</el-form-item>
					</el-form>
					<div class="receive-list">
						<p>接收人:</p>
						<el-form style="height:auto" ref="addMessageContacts" :model="messageContacts" :rules="rules">
							<div class="input-box">
								<el-form-item  prop="name">
									<el-input style="margin-right:15px" placeholder="user" v-model="messageContacts.name"/>
								</el-form-item>
								<el-form-item  prop="account">
									<el-input  placeholder="号码" v-model="messageContacts.account"/>
								</el-form-item  >
								<el-button @click="handleAddContacts(1)" type="primary">添加</el-button>
							</div>
						</el-form>
						<div class="data-list">
							<div class="data-item" v-for="user in messageReceiveList" :key="user.id">
								<el-tooltip :enterable="false" :show-after="1000">
									<template #content>{{user.contactName}} - {{user.contactAccount}}</template>
									<span @click="handleClickContacts(1,user)">{{user.contactName}} - {{ user.contactAccount }}</span>
								</el-tooltip>
								<SvgIcon name="ele-Delete" @click="delContacts(1,user)"/>
							</div>
						</div>
						<div class="btn-box">
							<el-button type="primary" @click="handleTest(1)">验证</el-button>
							<el-button type="danger" @click="resetSetting(1)">重置</el-button>
							<el-button type="primary" @click="handleSave(1)">保存</el-button>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script lang="ts" setup>
import { reactive, ref, watch } from 'vue';
import { ElMessage, FormInstance, FormRules } from 'element-plus';
import { useAlarmApi } from '/@/api/alarm';

export interface AppriseItem{
	id:number,
	contactType:number,
	contactName:string,
	contactAccount:string
}

interface MessageForm{
	id:string|number,
	serviceProvider: 'aliyun'|'tencent',
	domain: string,
	accessKeyId: string,
	accessKey: string,
	sign: string,
	templateCode: string,
	regionId: string,
	appId: string
}

interface EmailForm{
	id: string|number,
	stmpAddress: string,
	port: string,
	ssl: boolean,
	stmpUserName: string,
	stmpPwd: string,
	senderEmail: string
}

let emailReceiveList = ref<AppriseItem[]>([]);
let messageReceiveList = ref<AppriseItem[]>([]);
const serviceProvideOptions = ref<SelectOptionType[]>([
	{
		label: '腾讯云',
		value: 'tencent'
	},
	{
		label: '阿里云',
		value: 'aliyun'
	}
]);
const regionOptions = ref<SelectOptionType[]>([
	{
		label: '华北地区(北京)',
		value: 'ap-beijing'
	},
	{
		label: '华南地区(广州)',
		value: 'ap-guangzhou'
	},
	{
		label: '华东地区(南京)',
		value: 'ap-nanjing'
	}
]);
const messageFormRules = reactive<FormRules>({
	domain: [
		{ required: true, message: '不能为空', trigger: 'blur' },
	],
	accessKeyId: [
		{ required: true, message: '不能为空', trigger: 'blur' },
	],
	accessKey: [
		{ required: true, message: '不能为空', trigger: 'blur' },
	],
	sign: [
		{ required: true, message: '不能为空', trigger: 'blur' },
	],
	templateCode: [
		{ required: true, message: '不能为空', trigger: 'blur' },
	],
	regionId: [
		{ required: true, message: '不能为空', trigger: 'blur' }
	],
	appId: [
		{ required: true, message: '不能为空', trigger: 'blur' },
	],
});

const rules = reactive<FormRules>({
	name: [
		{ required: true, message: '不能为空', trigger: 'blur' },
	],
	account: [
		{ required: true, message: '不能为空', trigger: 'blur' },
	]

});

const messageForm = reactive<MessageForm>({
	id: '',
	serviceProvider: 'aliyun',
	domain: '',
	accessKeyId: '',
	accessKey: '',
	sign: '',
	templateCode: '',
	regionId: '',
	appId: ''
});
const isShowMessageItem = ref(messageForm.serviceProvider === 'tencent');
const messageSwitch = ref(false);
const emailSwitch = ref(false);
watch(
	() =>	messageForm.serviceProvider,
	(val) => {
		if (val === 'aliyun') {
			isShowMessageItem.value = false;
			messageForm.domain = 'dysmsapi.aliyuncs.com';
		} else {
			isShowMessageItem.value = true;
			messageForm.domain = 'sms.tencentcloudapi.com';
		}
	},
	{
		immediate: true,
	}
);

const checkPositiveInt = (rule:any, value:any, callback:any) => {
	if (!/^[0-9]\d*$/.test(value)) {
		return callback(new Error('只能输入正整数'));
	}
	callback();
};

const emailFormRules = reactive<FormRules>({
	stmpAddress: [
		{ required: true, message: '不能为空', trigger: 'blur' },
	],
	port: [
		{ required: true, message: '不能为空', trigger: 'blur' },
		{ required: true, validator: checkPositiveInt, trigger: 'blur' }
	],
	stmpUserName: [
		{ required: true, message: '不能为空', trigger: 'blur' },
	],
	stmpPwd: [{ required: true, message: '不能为空', trigger: 'blur' },
	],
	senderEmail: [
		{ required: true, message: '不能为空', trigger: 'blur' },
	]
});
const emailForm = reactive<EmailForm>({
	id: '',
	stmpAddress: '',
	port: '',
	ssl: false,
	stmpUserName: '',
	stmpPwd: '',
	senderEmail: ''
});

/**
 * init setting
 * @param type 0 emial  1 message 3 all
 */
const initSetting = (type?:0|1|3) => {
	useAlarmApi().getAlarmAppriseList({}).then((res) => {
		let emailSettings = res.data.records.find((item:any) => item.type === 0);
		emailReceiveList.value = emailSettings?.contacts || [];
		emailSettings.smtpPort ||= 25;

		let msgSettings = res.data.records.find((item:any) => item.type === 1);
		messageReceiveList.value = msgSettings?.contacts || [];

		if (type === 0) {
			initEmailSettings(emailSettings);
		} else if (type === 1) {
			initMsgSettings(msgSettings);
		} else {
			initEmailSettings(emailSettings);
			initMsgSettings(msgSettings);
		}
	});
};
initSetting(3);

const initMsgSettings = (data:any) => {
	if (!data) return;
	messageForm.serviceProvider = data.smsProvider;
	messageForm.domain = data.smsProviderHost;
	messageForm.accessKeyId = data.smsAccessId;
	messageForm.accessKey = data.smsAccessSecret;
	messageForm.sign = data.smsSignName;
	messageForm.regionId = data.smsRegion;
	messageForm.templateCode = data.smsTemplateCode;
	messageForm.appId = data.smsAppId;
	messageForm.id = data.id;
	messageSwitch.value = Boolean(data.status);
};

const initEmailSettings = (data:any) => {
	if (!data) return;
	emailForm.stmpAddress = data.smtpHost;
	emailForm.port = data.smtpPort;
	emailForm.ssl = Boolean(data.smtpSsl);
	emailForm.stmpUserName = data.smtpUsername;
	emailForm.stmpPwd = data.smtpPassword;
	emailForm.senderEmail = data.emailFrom;
	emailForm.id = data.id;
	emailSwitch.value = Boolean(data.status);
};

// contacts
const emailContactsInput = reactive({
	name: ''
});
const messageContacts = reactive({
	account: '',
	name: ''
});
// add contacts     0 email   1 message
const addEmailContact = ref<FormInstance>();
const addMessageContacts = ref<FormInstance>();

const handleAddContacts = (type:0|1) => {
	// 是否通过验证
	if (type === 0) {
		addEmailContact.value?.validate((valid:any) => {
			if (valid) {
				useAlarmApi().addAlarmContact({
					contactAccount: emailContactsInput.name,
					contactName: emailContactsInput.name,
					contactType: type
				}).then(() => {
					updateContacts(type);
					ElMessage.success(`新增联系人成功${emailContactsInput.name}`);
					emailContactsInput.name = '';
				});
			}
		});
	} else if (type === 1) {
		addMessageContacts.value?.validate((valid:any) => {
			if (valid) {
				useAlarmApi().addAlarmContact({
					contactAccount: messageContacts.account,
					contactName: messageContacts.name,
					contactType: type
				}).then(() => {
					updateContacts(type);
					ElMessage.success(`新增联系人成功${messageContacts.name}`);
					messageContacts.account = '';
					messageContacts.name = '';
				});
			}
		});
	}
};
const updateContacts = (type:0|1) => {
	useAlarmApi().getAlarmAppriseList({}).then((res) => {
		let contacts = res.data.records.find((item:any) => item.type === type).contacts;
		if (type === 0) {
			emailReceiveList.value = contacts;
		} else {
			messageReceiveList.value = contacts;
		}
	});
};
// delete contacts
const delContacts = (type:0|1, row:AppriseItem) => {
	useAlarmApi().deleteAlarmContact({ contactId: row.id }).then(() => {
		updateContacts(type);
		ElMessage.success(`删除联系人成功${row.contactName}`);
	});
};

// select concats
const handleClickContacts = (type:0|1, row:AppriseItem) => {
	if (!type) {
		emailContactsInput.name = row.contactAccount;
	} else {
		messageContacts.name = row.contactName;
		messageContacts.account = row.contactAccount;
	}
};

// send test
const handleTest = (type:0|1) => {
	!type && useAlarmApi().sendEmailTest().then(() => {
		ElMessage.success('发送邮件成功');
	});

	type && useAlarmApi().sendSmsTest().then(() => {
		ElMessage.success('发送短信成功');
	});
};

// save
const emailRef = ref<FormInstance>();
const messageRef = ref<FormInstance>();
const handleSave = (type:0|1) => {
	let data = !type ? {
		id: emailForm.id,
		smtpHost: emailForm.stmpAddress,
		smtpPort: emailForm.port,
		smtpSsl: Number(emailForm.ssl),
		smtpUsername: emailForm.stmpUserName,
		smtpPassword: emailForm.stmpPwd,
		emailFrom: emailForm.senderEmail,
		status: Number(emailSwitch.value),
		type
	} : {
		id: messageForm.id,
		smsProvider: messageForm.serviceProvider,
		smsProviderHost: messageForm.domain,
		smsAccessId: messageForm.accessKeyId,
		smsAccessSecret: messageForm.accessKey,
		smsSignName: messageForm.sign,
		smsTemplateCode: messageForm.templateCode,
		smsRegion: messageForm.regionId,
		smsAppId: messageForm.appId,
		status: Number(messageSwitch.value),
		type
	};

	if (!type) {
		emailRef.value && emailRef.value?.validate((valid) => {
			if (!valid) return;
			useAlarmApi().updateAlarmApprise(data).then(() => {
				initSetting(type);
				ElMessage.success('保存告警设置成功');
			});
		});
		return emailRef.value?.validate();
	} else {
		messageRef.value && messageRef.value?.validate((valid) => {
			if (!valid) return;
			useAlarmApi().updateAlarmApprise(data).then(() => {
				initSetting(type);
				ElMessage.success('保存告警设置成功');
			});
		});
		return messageRef.value?.validate();
	}
};

// reset setting
const resetSetting = (type:0|1) => {
	initSetting(type);
	if (!type) {
		emailRef.value?.clearValidate();
	} else {
		messageRef.value?.clearValidate();
	}
};

// trun on/off email setting
const emailSwitchChange = () => {
	handleSave(0)?.catch(() => {
		ElMessage.error('操作失败！告警设置填写错误');
	});
};
const messageSwitchChange = () => {
	handleSave(1)?.catch(() => {
		ElMessage.error('操作失败！告警设置填写错误');
	});
};
</script>

<style scoped lang="scss">
.container{
	display: flex;
	.email-setting, .message-setting{
		.title{
			display: flex;
			align-items: center;
			margin-bottom: 15px;
			span{
				font-size: 16px;
				font-weight: 900;
				margin-right: 35px;
			}
		}
		.form-box{
			display: flex;
			flex-direction: column;
			justify-content: space-between;
			height: 380px;

			form{
				max-height: 250px;
				overflow: auto;
			}

			position: relative;
			margin-right:2px;
			.receive-list{
				position: relative;
				p{
					margin-bottom: 10px;
				}
				.input-box{
					display: flex;
					.el-button{
						margin-left: 10px;
					}
				}
				.data-list{
					width: 50%;
					margin-top: 15px;
					height: 85px;
					overflow-y: auto;
					padding: 5px;
					border-radius: var(--el-input-border-radius,var(--el-border-radius-base));
					border: 1px solid var(--el-border-color);
					.data-item{
						display: flex;
						justify-content: space-between;
						cursor: default;
						margin-bottom: 5px;
						&:hover{
								span{
									color: var(--el-color-primary);
								}
							}
						span{
							font-size: 15px;
							letter-spacing: 1px;
							display: inline-block;
							width: 250px;
							overflow: hidden;
							text-overflow: ellipsis;
							white-space: nowrap;

						}
						i{
							font-size: 17px !important;
							:hover{
								cursor: pointer;
								color: var(--el-color-danger);
							}
						}
					}
				}
			}
		}
		.btn-box{
			margin-top: 20px;
			position: absolute;
			right: 20px;
			bottom: 2px;
		}
	}
	.message-setting{
		margin-right: 0px;
	}
}
:deep(.el-form-item__content) {
	width: 205px;
}
</style>